# coding=utf-8
from django.conf import settings
import sys, hashlib,os
import redis

reload(sys)
sys.setdefaultencoding('utf-8')


class redis_data(object):
	def __init__(self):
		self.mc = redis.Redis(host='172.16.30.45', port=6379, db=0)

	def key_import(self,key,value): ##通用函数，导入KEY，VALUE

		if self.mc.exists(key):  ##是否存在key，否则从 配置文件再次注入KEY，防止redis重启
			self.mc.delete(key)
			self.mc.set(key,value)
		else:
			self.mc.set(key,value)
		return

	def key_output(self,key): ##通用函数, 导出KEY的值
		if self.mc.exists(key):  ##是否存在key，否则从 配置文件再次注入KEY，防止redis重启
			return self.mc.get(key)
		else:
			return 0


	def source_import(self):
		filename = os.path.join(settings.TEMPLATES[0]['DIRS'][0],'conf','data_source.txt')
		f=open(filename,'r')
		_list=[]
		for i in f:
			_list.append({'source':i.split(',')[1],'select':''})   ##生成数据源列表格式 {'select':"",'source':'金银建'}
		self.mc.set(self.key,_list)

		return _list

	def source_key(self):
		self.key = "city_source"  ##城市数据源在redis中的KEY名
		if self.mc.exists(self.key):  ##是否存在key，否则从 配置文件再次注入KEY，防止redis重启
			_data = self.mc.get(self.key)
			return eval(_data)
		else:
			_data=self.source_import()
			return _data


	def multiple_source(self,source):
		if source.find('+') != -1:
			source_list=source.split('+')

			if source.rfind('rl') != -1:  ##如果是 热力图
				_list=[]
				for i in source_list:
					if i.find('rl') == -1:  ##如果在数据源名称 没有找到 rl 关键字
						_list.append(i+'rl')
					_list.append(i)
				source_list=_list

			print source_list[0]

			_datadict = eval(self.point_source(source_list[0]))  ##用第一个数据源作为初始数据
			list1 = _datadict['gps_list']
			time_str = _datadict['time']
			timeid = _datadict['timeid']
			source = _datadict['source']
			cars = _datadict['cars']
			data_total = _datadict['data_total']
			citycode=_datadict['citycode']

			for i in source_list[1:]:
				print i

				_datadict = eval(self.point_source(i))
				list1 = _datadict['gps_list']+list1
				time_str = _datadict['time']

				source = _datadict['source']

				cars = _datadict['cars']+cars
				data_total = _datadict['data_total']+data_total

			_dict={'time':time_str,'timeid':timeid,'citycode':citycode,'source':source,'gps_list':list1,\
			'cars':cars,'data_total':data_total}

			return _dict

		return 0

	def point_source(self,source):
		source=source.encode('gbk')

		_dict=self.multiple_source(source)
		if _dict:
			return _dict

		md = hashlib.md5()
		md.update(source)
		key = md.hexdigest()
		if self.mc.exists(key):
			return self.mc.get(key)
		else:
			return None
